import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:uikit/utils/image_util/image_convert.dart';

import '../../extension/ui_extension.dart';
import '../../uikit.dart';
import '../../widgets/image/anchor_image.dart';

/// * 建议，使用[ScaleType.scaleByWidth] 可以最大限度的保证缩放质量
/// * [ScaleType.scaleByWidth] 标准：一屏宽度的targetWidth 为1440（实际使用时可以灵活配置，但最大为1440）。
///  eg. 设计图上一个图片占1/2屏幕宽度，那么它的[targetWidth] 就是720.
///  [useOriginImg] 应为 false, [scaleType] 应为 [ScaleType.scaleByWidth]
/// [useOriginImg] 为true 将直接加载链接原图
/// [scaleRatio] < 100 为缩小， > 100 为放大
/// * [ScaleType] 缩放方式：按系数还是按宽度进行等比缩放. 默认[ScaleType.scaleByRatio]
/// * [targetWidth] 按指定宽度 等比缩小，大于原图，将使用原图
/// * 注意，宽度、系数缩放只能二选一，同时宽度只有缩小，若大于原图，将使用原图
/// * [cacheKey] 缓存标识，为空则使用url

/// 缩放方式
/// * 目前来看，使用比例缩放
enum ScaleType {
  // 按宽度，小于原图则使用原图
  scaleByWidth,

  // 按比例缩放
  scaleByRatio,
}

class ImageUtil with ImageConvert {
  static const String _defaultImg = 'lib/assets/state/img_loading_error.webp';
  //R.libAssetsStateImgLoadingError;

  static const BlendMode colorBlendMode = BlendMode.srcATop;

  static const String key = 'rikiCachedImageData';

  /// 图片缓存管理器
  static CacheManager? cacheManager;

  /// 初始化一个图片缓存管理器
  /// * 可以考虑根据机器配置增加多种配置
  static void initCacheManager(CacheManager cm) {
    assert(cacheManager == null, 'Cache manager can only init once !');
    cacheManager = cm;
  }

  /// 加载网络图片
  static Widget loadNetworkImage(
    String imageUrl, {
    Key? key,
    double? width,
    double? height,
    String? cacheKey,
    BoxFit fit = BoxFit.cover,
    @Deprecated('已弃用，请使用customHolderWidget') String? holderImg,
    Widget? customHolderWidget,
    Widget? customErrorWidget,
    String? package,
    Color? color,
    BlendMode colorBlendMode = colorBlendMode,
    Duration duration = const Duration(milliseconds: 500),
    ScaleType scaleType = ScaleType.scaleByRatio,
    int? targetWidth,
    bool useOriginImg = true,
    int scaleRatio = 50,
  }) {
    assert(cacheManager != null, 'Must init cache manager before use it.');
    holderImg ??= _defaultImg;
    package = holderImg == _defaultImg ? RikiUikit.PACKAGE : package;
    if (imageUrl.trim() == '') {
      return customErrorWidget ?? ImageConvert.retrieveCommonImgErrorWidget(key: key, width: width, height: height);
    }
    return CachedNetworkImage(
      key: key,
      cacheManager: cacheManager,
      cacheKey: cacheKey,
      width: width,
      height: height,
      fadeInDuration: duration,
      fadeOutDuration: duration,
      fit: fit,
      color: color,
      colorBlendMode: colorBlendMode,
      imageUrl: useOriginImg
          ? imageUrl
          : ImageConvert.formatImgURL(
              imageUrl,
              scaleType,
              scaleRatio: scaleRatio,
              targetWidth: targetWidth,
            ),
      placeholder: (BuildContext context, String url) => customHolderWidget ?? ImageConvert.retrieveCommonPlaceholder(),
      errorWidget: (BuildContext context, String url, dynamic error) =>
          customErrorWidget ??
          ImageConvert.retrieveCommonImgErrorWidget(
            key: key,
            width: width,
            height: height,
          ),
    );
  }

  /// 自定义占位图的加载图片
  static Widget loadImageCustomPlaceHolder(
    String imageUrl, {
    Key? key,
    double? width,
    double? height,
    Widget? placeHolderWidget,
    String? cacheKey,
    BoxFit fit = BoxFit.fill,
    Color? color,
    BlendMode colorBlendMode = colorBlendMode,
    String? package,
    Duration duration = const Duration(milliseconds: 500),
    ScaleType scaleType = ScaleType.scaleByRatio,
    int? targetWidth,
    bool useOriginImg = true,
    int scaleRatio = 50,
  }) {
    assert(cacheManager != null, 'Must init cache manager before use it.');
    if (imageUrl.trim() == '') {
      return placeHolderWidget ?? RikiEmpty.ui;
    }
    if (imageUrl.startsWith('http')) {
      return CachedNetworkImage(
        key: key,
        cacheManager: cacheManager,
        cacheKey: cacheKey,
        width: width,
        height: height,
        fadeInDuration: duration,
        fadeOutDuration: duration,
        fit: fit,
        color: color,
        colorBlendMode: colorBlendMode,
        imageUrl: useOriginImg
            ? imageUrl
            : ImageConvert.formatImgURL(
                imageUrl,
                scaleType,
                scaleRatio: scaleRatio,
                targetWidth: targetWidth,
              ),
        placeholder: (BuildContext context, String url) => placeHolderWidget ?? RikiEmpty.ui,
        errorWidget: (BuildContext context, String url, dynamic error) => ImageConvert.retrieveCommonImgErrorWidget(
          key: key,
          width: width,
          height: height,
        ),
      );
    } else {
      return loadAssetImage(
        imageUrl,
        width: width,
        height: height,
        fit: fit,
        color: color,
        colorBlendMode: colorBlendMode,
        package: package,
      );
    }
  }

  /// 无占位图的加载网络图片
  static Widget loadImageNoHolder(
    String imageUrl, {
    Key? key,
    required double width,
    required double height,
    BoxFit fit = BoxFit.cover,
    required Color color,
    BlendMode colorBlendMode = colorBlendMode,
    Duration duration = const Duration(milliseconds: 500),
    ScaleType scaleType = ScaleType.scaleByRatio,
    int? targetWidth,
    bool useOriginImg = true,
    int scaleRatio = 50,
    String? cacheKey,
  }) {
    assert(cacheManager != null, 'Must init cache manager before use it.');
    return CachedNetworkImage(
      key: key,
      cacheManager: cacheManager,
      cacheKey: cacheKey,
      width: width,
      height: height,
      fadeInDuration: duration,
      fadeOutDuration: duration,
      fit: fit,
      color: color,
      colorBlendMode: colorBlendMode,
      imageUrl: useOriginImg
          ? imageUrl
          : ImageConvert.formatImgURL(
              imageUrl,
              scaleType,
              scaleRatio: scaleRatio,
              targetWidth: targetWidth,
            ),
    );
  }

  /// 锚点图片
  static Widget loadImageWithAnchor(
    String imageUrl, {
    List<AnchorWidget> anchors = const <AnchorWidget>[],
    double? width,
    double? height,
    Widget? placeHolderWidget,
    Widget? customErrorWidget,
    String? cacheKey,
    BoxFit fit = BoxFit.fill,
    Color? color,
    BlendMode colorBlendMode = colorBlendMode,
    String? package,
    Duration duration = const Duration(milliseconds: 500),
    ScaleType scaleType = ScaleType.scaleByRatio,
    int? targetWidth,
    bool useOriginImg = true,
    int scaleRatio = 50,
  }) {
    assert(cacheManager != null, 'Must init cache manager before use it.');
    if (imageUrl.trim() == '') {
      return placeHolderWidget ?? RikiEmpty.ui;
    }
    if (imageUrl.startsWith('http')) {
      return AnchorImageWidget(
        imageType: AnchorImageType.net,
        anchors: anchors,
        imageUrl: useOriginImg ? imageUrl : ImageConvert.formatImgURL(imageUrl, scaleType, scaleRatio: scaleRatio, targetWidth: targetWidth),
        width: width,
        height: height,
        cacheKey: cacheKey,
        placeHolderWidget: placeHolderWidget,
        customErrorWidget: customErrorWidget,
        fit: fit,
        color: color,
        colorBlendMode: colorBlendMode,
      );
    } else {
      return loadAssetImage(
        imageUrl,
        width: width,
        height: height,
        fit: fit,
        color: color,
        colorBlendMode: colorBlendMode,
        package: package,
        withAnchor: true,
        anchors: anchors,
      );
    }
  }

  /// 加载本地资源图片
  static Widget loadAssetImage(
    String name, {
    Key? key,
    double? width,
    double? height,
    BoxFit? fit,
    Color? color,
    String? package,
    BlendMode colorBlendMode = colorBlendMode,
    bool withAnchor = false,
    List<AnchorWidget> anchors = const <AnchorWidget>[],
  }) {
    if (withAnchor) {
      return AnchorImageWidget(
        imageUrl: name,
        anchors: anchors,
        imageType: AnchorImageType.asset,
        height: height,
        width: width,
        fit: fit ?? BoxFit.fill,
        color: color,
        colorBlendMode: colorBlendMode,
        package: package,
      );
    }
    return Image.asset(
      name,
      key: key,
      height: height,
      width: width,
      fit: fit,
      color: color,
      colorBlendMode: colorBlendMode,
      package: package,
    );
  }

  ///获取ImageProvider对象
  static ImageProvider getImageProvider(String? imageUrl, {String? package, String? holderImg, String? cacheKey}) {
    holderImg ??= _defaultImg;
    package = holderImg == _defaultImg ? RikiUikit.PACKAGE : package;
    if (imageUrl == null || imageUrl.trim() == '') {
      return AssetImage(holderImg, package: package);
    }
    return CachedNetworkImageProvider(imageUrl, cacheManager: cacheManager, cacheKey: cacheKey);
  }
}
